package net.hhk.twitter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import net.hhk.connect.HTTPConnect;
import net.hhk.controller.SuggestAdapter;
import net.hhk.controller.lazyload.ImageLoader;
import net.hhk.data.Base64;
import net.hhk.data.Constant;
import net.hhk.data.User;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.LocalActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

public class EditProfileActivity extends Activity implements OnClickListener {
	private User user;
	private EditText fullname, bio, web, location;
	private ImageView avatar;
	private ImageLoader imageLoader;
	private Bitmap photoSdc = null;
	private String ImageUrl = "";
	private Context context = this;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_profile);
		imageLoader = new ImageLoader(this);
		Bundle b = getIntent().getExtras();
		user = new User();
		user.setUserid(b.getInt("id"));
		user.setFullname(b.getString("name"));
		String avatarUrl = b.getString("avatar");
		user.setNoHostAvatar(avatarUrl.substring(Constant.HOST.length()).trim());
		user.setBio(b.getString("bio"));
		user.setWeb(b.getString("website"));
		user.setLocation(b.getString("location"));
		showPreInfo();

		LinearLayout write_tweet = (LinearLayout) findViewById(R.id.home_write_tweet);
		write_tweet.setOnClickListener(clickWriteTweet);

		Button btn = (Button) findViewById(R.id.btn_tweet);
		btn.setOnClickListener(clickWriteTweet);
		
		LinearLayout searchLayout = (LinearLayout) findViewById(R.id.btnSearch_layout);
		searchLayout.setOnClickListener(clickSearch);
		Button btnSearch = (Button) findViewById(R.id.btn_search);
		btnSearch.setOnClickListener(clickSearch);

	}

	private OnClickListener clickWriteTweet = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent i = new Intent(getApplicationContext(),
					WriteTweetActivity.class);
			Bundle b = new Bundle();

			b.putInt("isReply", 0);
			i.putExtras(b);
			startActivity(i);

		}
	};
	private OnClickListener clickSearch = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent i = new Intent(getApplicationContext(), SearchActivity.class);

			startActivity(i);

		}
	};

	public void showPreInfo() {
		fullname = (EditText) findViewById(R.id.reg_fullname);
		fullname.setText(user.getFullname());
		bio = (EditText) findViewById(R.id.reg_bio);
		bio.setText(user.getBio());
		web = (EditText) findViewById(R.id.reg_web);
		web.setText(user.getWeb());
		location = (EditText) findViewById(R.id.reg_location);
		location.setText(user.getLocation());

		avatar = (ImageView) findViewById(R.id.write_image_profile);
		imageLoader.DisplayImage(Constant.HOST + user.getAvatar(), avatar);

		LinearLayout change_profile = (LinearLayout) findViewById(R.id.change_profile);
		change_profile.setOnClickListener(this);

		Button save = (Button) findViewById(R.id.edit_profile_save);
		save.setOnClickListener(this);

		Button cancel = (Button) findViewById(R.id.edit_profile_cancel);
		cancel.setOnClickListener(this);

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.change_profile:
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
			intent.setType("image/*");
			intent.putExtra("return-data", true);
			startActivityForResult(intent, 1);
			break;
		case R.id.edit_profile_save:
			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
					context);

			alertDialogBuilder
					.setMessage("Are you sure want to save change")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									if (ImageUrl.length() > 0) {
										String oldImageUrl = user.getAvatar()
												.trim();
										deleteImageInServer(oldImageUrl);
									}
									changeProfile();
									finish();
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									// if this button is clicked, just
									// close
									// the dialog box and do nothing
									dialog.cancel();
								}
							});

			// create alert dialog
			AlertDialog alertDialog = alertDialogBuilder.create();

			// show it
			alertDialog.show();

			break;
		case R.id.edit_profile_cancel:
			AlertDialog.Builder alertDialogBuilder2 = new AlertDialog.Builder(
					context);

			alertDialogBuilder2
					.setMessage("Are you sure want to cancel editting profile")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									if (ImageUrl.length() > 0)
										deleteImageInServer(ImageUrl);
									finish();
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									// if this button is clicked, just
									// close
									// the dialog box and do nothing
									dialog.cancel();
								}
							});

			// create alert dialog
			AlertDialog alertDialog2 = alertDialogBuilder2.create();

			// show it
			alertDialog2.show();

			break;

		default:
			break;
		}
	}

	protected void onActivityResult(int requestCode, int resultCode,
			android.content.Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case 1:
			if (requestCode == 1 && data != null && data.getData() != null) {
				Uri _uri = data.getData();

				if (_uri != null) {
					// User had pick an image.
					Cursor cursor = getContentResolver()
							.query(_uri,
									new String[] { android.provider.MediaStore.Images.ImageColumns.DATA },
									null, null, null);
					cursor.moveToFirst();

					// Link to the image
					final String imageFilePath = cursor.getString(0);

					File photos = new File(imageFilePath);
					photoSdc = decodeFile(photos);
					// b = Bitmap.createScaledBitmap(b, 150, 150, true);
					if (photoSdc != null) {
						avatar.setImageBitmap(photoSdc);
						uploadPicture();

					}
					cursor.close();

				}
			}
			break;

		}

	};

	private Bitmap decodeFile(File f) {
		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 70;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale++;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}

	public void changeProfile() {
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		nameValuePairs.add(new BasicNameValuePair("screenName", fullname
				.getText().toString()));
		nameValuePairs.add(new BasicNameValuePair("bio", bio.getText()
				.toString()));
		nameValuePairs.add(new BasicNameValuePair("location", location
				.getText().toString()));
		nameValuePairs.add(new BasicNameValuePair("website", web.getText()
				.toString()));
		if (ImageUrl.length() > 0)
			nameValuePairs.add(new BasicNameValuePair("avatar", ImageUrl));
		else
			nameValuePairs.add(new BasicNameValuePair("avatar", user
					.getAvatar()));
		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.POST_CHANGE_PROFILE,
				nameValuePairs);

	}

	public void uploadPicture() {
		AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPreExecute()
			 */
			@Override
			protected void onPreExecute() {
				super.onPreExecute();

			}

			@Override
			protected String doInBackground(String... params) {
				// Following actions will be done in background
				if (photoSdc != null)
					return UploadBitmapToServer(photoSdc);
				else
					return "";
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
			 */
			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				ImageUrl = result.trim();

			}
		};
		asyncTask.execute("Saurabh");
	}

	public String UploadBitmapToServer(Bitmap bm) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 90, stream); // compress to
																// which
																// format you
																// want.
		byte[] byte_arr = stream.toByteArray();
		String image_str = Base64.encodeBytes(byte_arr);
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		nameValuePairs.add(new BasicNameValuePair("imageBinary", image_str));
		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.POST_IMAGE, nameValuePairs);
		return result;
	}

	public void deleteImageInServer(String url) {
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		nameValuePairs.add(new BasicNameValuePair("dir_file", url));
		HTTPConnect http = HTTPConnect.getConnect();
		String result = http.doConnect(Constant.DELETE_IMAGE, nameValuePairs);
	}

}
